﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Timesheet.Domain;
using Timesheet.Service;

namespace Timesheet.WebForm.TimeSheets
{
    public partial class New:System.Web.UI.Page
    {
        public ITimeSheetsService _Service { get; set; }
        public IProjectService _PrjService { get; set; }
        public ITeamService _TeamService { get; set; }
        private long _CopyTmsh;
        private long prjID;
        private long team;
        private Timesheet.Domain.TimeSheets _CurrentTmsh;
        protected void Page_Load(object sender,EventArgs e)
        {

            if (!IsPostBack)
            {
                var user = (User)Session["User"];
                if (user == null)
                    Response.Redirect("~/Account/Login.aspx");
                IList<Project> companies = _PrjService.GetActivedRefProjects(user.Id);
                cbxProjectID.DataSource = companies;
                cbxProjectID.ValueField = "PrjID";
                cbxProjectID.ValueType = typeof(Int64);
                cbxProjectID.TextField = "ProjectName";
                cbxProjectID.DataBindItems();

                DateTime date = DateTime.Now;
                if (!string.IsNullOrEmpty(Request.Params["date"]))
                    date = DateTime.Parse(Request.Params["date"]);
                if (!string.IsNullOrEmpty(Request.Params["tmsh"]))
                {
                    _CopyTmsh = Int64.Parse(Request.Params["tmsh"]);
                    fldWeek.Value = date;
                }
            }


            lblMessage.Visible = false;
            _CopyTmsh = -1;
           
            if(Request.Params["msg"] != null)
            {
                
                lblMessage.Visible = true;
                lblMessage.Text = Request.Params["msg"];                              
            }
            prjID = -1;
            team = -1;
            lblTeamID.Visible = false;
            lblProjectID.Visible = false;
            cbxProjectID.Visible = false;
            cbxTeam.Visible = false;
            if(!string.IsNullOrEmpty(Request.Params["prjID"]) && !string.IsNullOrEmpty(Request.Params["team"]))
            {
                lblTeamID.Visible = true;
                lblProjectID.Visible = true;
                prjID = Int64.Parse(Request.Params["prjID"]);
                team = Int64.Parse(Request.Params["team"]);                   
                var teamObj =_TeamService.GetByID(team);
                if(teamObj!=null)
                lblTeamID.Text = teamObj.TeamName;
                var prjObj =_PrjService.GetByID(prjID);
                if(prjObj !=null)
                lblProjectID.Text = prjObj.ProjectName;
            }
            else
            {
                cbxTeam.Visible = true;
                cbxProjectID.Visible = true;
            }
                       
        }

        protected void btnNew_Click(object sender,EventArgs e)
        {
            DateTime selectedDate = fldWeek.Date;
            _CopyTmsh = Int64.Parse(Request.Params["tmsh"] ?? "-1");
            int doW = (int)selectedDate.DayOfWeek;
            DateTime from;
            if(cbxProjectID.Visible)
            {
                if(cbxProjectID.Value == null || cbxTeam.Value == null)
                {
                    Response.Redirect("New.aspx?msg=Please enter Project and Team");
                }
                if(cbxProjectID.Value == null)
                {
                    Response.Redirect("New.aspx?msg=Please enter Project");
                }
                else if(cbxTeam.Value == null)
                {
                    Response.Redirect("New.aspx?msg=Please enter Team");
                }
            }
            try
            {
                from = selectedDate.AddDays(-doW);
            }
            catch(Exception)
            {
                Response.Redirect("New.aspx?msg=Please enter day");
                return;
            }
            
            _CurrentTmsh = new Domain.TimeSheets()
            {
                CreateBy = Convert.ToInt64(Session["UserId"]),
                Active = true,
                Level = Session["userrole"] + "",
                ProjectID = _CopyTmsh!=-1?prjID:cbxProjectID.Visible?long.Parse(cbxProjectID.Value+""):prjID,
                Status = "0",
                TeamID =_CopyTmsh!=-1?team : cbxTeam.Visible?long.Parse(cbxTeam.Value+""):team,
                To = from.AddDays(6),
                From = from,
                Week = from.ToString("MM/dd/yyyy") + " - " + from.AddDays(6).ToString("MM/dd/yyyy")
            };

            prjID = _CurrentTmsh.ProjectID;
            Domain.TimeSheets lastedTimesheet = _Service.GetLastedTimesheet(prjID);
            Domain.TimeSheets sameWeekTimesheet = _Service.GetLastedTimesheet(prjID, _CurrentTmsh.Week);

            if (sameWeekTimesheet != null)
            {
                _CurrentTmsh.Ticket = sameWeekTimesheet.Ticket;
            }
            else
            {
                if (lastedTimesheet == null)
                {
                    Project pro = _PrjService.GetByID(prjID);
                    if (pro != null)
                        _CurrentTmsh.Ticket = pro.Ticket;
                    else
                        _CurrentTmsh.Ticket = 1;
                }
                else
                    _CurrentTmsh.Ticket = lastedTimesheet.Ticket + 1;
            }

            var result = _Service.Add(_CurrentTmsh);

            if(result)
            {
                if(_CopyTmsh != -1)
                {
                    _Service.CopyFrom(_CopyTmsh,_CurrentTmsh);
                }
                Response.Redirect("Lines.aspx?tmshID=" + _CurrentTmsh.Id);                
            }
            else
            {
                if(team==-1)
                {
                    Response.Redirect("New.aspx?msg=The week <" + _CurrentTmsh.Week + "> is already created, please try again");
                }
                Response.Redirect("New.aspx?"+(_CopyTmsh!=-1?("tmsh="+_CopyTmsh+"&"):"")+"team="+team+"&prjID="+prjID+"&msg=The week <" + _CurrentTmsh.Week + "> is already created, please try again");
            }
        }

        protected void dsPrjects_ObjectCreating(object sender,ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = _PrjService;
        }
        protected void dsTeams_ObjectCreating(object sender,ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = _TeamService;
        }

        protected void cbxProjectID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbxProjectID.SelectedItem != null)
            {
                long idProject = (Int64)cbxProjectID.SelectedItem.Value;
                var user = (User)Session["User"];
                IList<Team> branches = _TeamService.GetRefTeams(idProject, user);
                cbxTeam.DataSource = branches;
                cbxTeam.ValueField = "Id";
                cbxTeam.ValueType = typeof(Int64);
                cbxTeam.TextField = "TeamName";
                cbxTeam.DataBindItems();
            }
        }
       
    }
}